package com.issc.framework.helper;

import com.issc.framework.util.ReflectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 获取类和类的对象的映射放入Map集合中
 * 以及获取bean实例
 */
public final class BeanHelper {
    private static final Logger log = LoggerFactory.getLogger(BeanHelper.class);
    //创建map集合放入类和对象的映射
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>(100);

    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class<?> clz : beanClassSet) {
            Object object = ReflectionUtil.newInstance(clz);
            BEAN_MAP.put(clz, object);
        }
    }

    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    /**
     * 获取bean实例
     *
     * @param clz   类对象
     * @param <T>类型
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeanInstance(Class<T> clz) {
        if (!BEAN_MAP.containsKey(clz)) {
            log.error("can't get bean by class", clz);
            throw new RuntimeException("can't get bean by class" + clz);
        }
        return (T) BEAN_MAP.get(clz);
    }

    public static void setBean(Class<?> clz, Object object) {
        BEAN_MAP.put(clz, object);
    }
}
